<template>
  <div class="qiniu">
    <input @change="uploadInputchange"  id="uploadFileInput" type="file" accept="image/*">
    <img :src="imgUrl"/>
  </div>
</template>

<script type="text/ecmascript-6">
//参考文章: https://www.jianshu.com/p/6d21a54fbfbd

import axios from "axios";
import api from "@/api/api";

const URL = "http://resource.caomudai.com/"

export default {
  
  data() {
    return {
      token: null,
      imgUrl: null
    };
  },
  created() {
    this._getUploadToken();
  },
  methods: {
    //触发input change事件
    uploadInputchange() {
      let file = document.getElementById("uploadFileInput").files[0]; //选择的图片文件
      this.uploadImgToQiniu(file);
    },
    //上传图片到七牛
    uploadImgToQiniu(file) {
      const axiosInstance = axios.create({ withCredentials: false }); //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
      let data = new FormData();
      data.append("token", this.token); //七牛需要的token，叫后台给，是七牛账号密码等组成的hash
      data.append("file", file);
      axiosInstance({
        method: "POST",
        url: "http://upload.qiniup.com/", //上传地址
        data: data,
        timeout: 30000, //超时时间，因为图片上传有可能需要很久
        onUploadProgress: progressEvent => {
          //imgLoadPercent 是上传进度，可以用来添加进度条
          let imgLoadPercent = Math.round(
            progressEvent.loaded * 100 / progressEvent.total
          );
        }
      })
        .then(response => {
          // document.getElementById("uploadFileInput").value = ""; //上传成功，把input的value设置为空，不然 无法两次选择同一张图片
          //上传成功...  (登录七牛账号，找到七牛给你的 URL地址) 和 data里面的key 拼接成图片下载地址
          console.log(response.data)
          this.imgUrl = URL + response.data.key;
        })
        .catch(function(err) {
          //上传失败
        });
    },
    _getUploadToken() {
      api.getUploadToken().then(response => {
        this.token = response;
        console.log(this.token)
      });
    }
  }
};
</script>

<style lang="less">
.qiniu {
  img {
    width: 300px;
    height: 300px;
    border: 1px dashed #666;
  }
}
</style>
